package com.yaoran.userauth.config.shiro;

import com.yaoran.userauth.config.redis.RedisUtils;
import com.yaoran.userauth.entity.User;
import com.yaoran.userauth.service.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;


public class UserRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(UserRealm.class);
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection){
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String loginName = (String) authenticationToken.getPrincipal();

        String password = new String((char[]) authenticationToken.getCredentials());
        User user = loginService.getUserByName(loginName);
        //根据用户名获取盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(loginName);
        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(user,user.getPassword(), getName());
        redisUtils.add(loginName, BeanMap.create(user));
        return simpleAuthenticationInfo;
    }
}
